package com.modern.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.modern.service.AnswerManager;
import com.modern.model.Answer;
import com.modern.webapp.action.BaseAction;

import java.util.List;

public class AnswerAction extends BaseAction implements Preparable {
    private AnswerManager answerManager;
    private List answers;
    private Answer answer;
    private Long  answerId;

    public void setAnswerManager(AnswerManager answerManager) {
        this.answerManager = answerManager;
    }

    public List getAnswers() {
        return answers;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String answerId = getRequest().getParameter("answer.answerId");
            if (answerId != null && !answerId.equals("")) {
                answer = answerManager.get(new Long(answerId));
            }
        }
    }

    public String list() {
        answers = answerManager.getAll();
        return SUCCESS;
    }

    public void setAnswerId(Long  answerId) {
        this. answerId =  answerId;
    }

    public Answer getAnswer() {
        return answer;
    }

    public void setAnswer(Answer answer) {
        this.answer = answer;
    }

    public String delete() {
        answerManager.remove(answer.getAnswerId());
        saveMessage(getText("answer.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (answerId != null) {
            answer = answerManager.get(answerId);
        } else {
            answer = new Answer();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (answer.getAnswerId() == null);

        answerManager.save(answer);

        String key = (isNew) ? "answer.added" : "answer.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}